<template>
  <el-card shadow="hover" class="card-margin">
    <el-form
      label-width="120px"
      ref="formRef"
      :model="formData"
      :rules="formDataRules"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input
          placeholder="请输入SPU名称"
          size="small"
          v-model="formData.spuName"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select size="small" v-model="formData.tmId">
          <el-option
            v-for="trademark in spuTrademarkList"
            :key="trademark.id"
            :label="trademark.tmName"
            :value="trademark.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="SPU描述"
          v-model="formData.description"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <!-- SPU图片上传 -->
        <el-upload
          class="upload-demo"
          list-type="picture-card"
          :action="`${BASEURL}/admin/product/upload`"
          :file-list="newSpuImageList"
          :on-preview="handlePreview"
          :on-success="uploadSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <i slot="default" class="el-icon-plus"></i>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-upload>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select size="small" v-model="addSaleAttrItem">
          <el-option
            v-for="baseSaleAttr in newBaseSaleAttrList"
            :key="baseSaleAttr.id"
            :label="baseSaleAttr.name"
            :value="`${baseSaleAttr.id}:${baseSaleAttr.name}`"
          />
        </el-select>
        <el-button
          class="btn-margin"
          type="primary"
          size="small"
          :disabled="!addSaleAttrItem"
          @click="addSaleAttrItemHandle"
          >添加销售属性</el-button
        >
        <el-table :data="formData.spuSaleAttrList" border class="table-margin">
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="60px"
          />
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            align="center"
            width="100px"
          />
          <el-table-column label="属性值名称列表">
            <template v-slot="{ row, $index }">
              <el-tag
                class="tag-margin"
                v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
                :key="index"
                closable
                type="success"
                @close="removeSaleAttrValue(row, index)"
              >
                {{ saleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                ref="btnRef"
                class="sale-btn"
                size="small"
                v-if="row.isShow"
                v-model="saleAttrName"
                @blur="loseBlur(row, $index)"
              />
              <el-button
                v-else
                class="el-icon-plus"
                size="small"
                @click="addSaleAttrValue(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100px" align="center">
            <template v-slot="{ $index }">
              <el-button
                class="el-icon-delete"
                type="danger"
                size="small"
                @click="removeSaleAttr($index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="saveSpu">保存</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  name: "AddSku",
  data() {
    return {
      BASEURL: process.env.VUE_APP_BASE_API,
      dialogVisible: false,
      dialogImageUrl: "",
      baseSaleAttrList: [],
      spuTrademarkList: [],
      saleAttrName: "",
      addSaleAttrItem: "",
      formData: {},
      formDataRules: {
        spuName: [
          { required: true, message: "请输入SPU名称", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入SPU描述", trigger: "blur" },
        ],
        tmId: [{ required: true, message: "请选择品牌信息" }],
        baseSaleAttrId: undefined,
        spuImageList: [
          { required: true, validator: this.spuImageListValidator },
        ],
        spuSaleAttrList: [
          { required: true, validator: this.spuSaleAttrListValidator },
        ],
      },
    };
  },
  mounted() {
    this.getBaseSaleAttrList();
    this.getSpuTrademarkList();
    // 修改Spu的时候，初始化formData数据为vuex中的数据
    this.formData = this.spuSaleAttrListItem;
    if (this.formData.id) {
      this.getSpuImageList(this.formData.id);
      this.getSpuSaleAttrList(this.formData.id);
    }
  },
  methods: {
    ...mapMutations("spu", ["RESET_SPUSALEATTRLISTITEM"]),
    ...mapActions("spu", ["getSpuImageList", "getSpuSaleAttrList"]),
    // 保存SPU
    async saveSpu() {
      await this.$refs.formRef.validate();
      const params = {
        ...this.formData,
        category3Id: this.category3Id,
        spuImageList: this.formData.spuImageList.map((item) => ({
          imaName: item.name,
          imgUrl: item.response.data,
        })),
      };
      if (!this.formData.id) {
        await this.$api.addSpu(params)
      } else {
        await this.$api.updateSpu(params)
      }
      this.$message({
        message: `${this.formData.id ? "修改" : "添加"}SPU成功`,
        type: "success",
      });
      this.$bus.$emit("updateIsShow", "SpuList");
    },
    // 取消按钮--回到SPU列表页面
    close() {
      this.$bus.$emit("updateIsShow", "SpuList");
      // 重置Vuex中的form表单数据
      this.RESET_SPUSALEATTRLISTITEM();
    },
    // SPU图片校验规则
    spuImageListValidator(rule, spuImageList, callback) {
      if (!spuImageList.length) {
        callback(new Error("请至少上传一张SPU图片"));
        return;
      }
      callback();
    },
    // SPU销售属性校验规则
    spuSaleAttrListValidator(rule, spuSaleAttrList, callback) {
      if (!spuSaleAttrList.length) {
        callback(new Error("请至少添加一条SPU销售属性"));
        return;
      }
      if (
        !spuSaleAttrList.some(
          (spuSaleAttr) => spuSaleAttr.spuSaleAttrValueList.length
        )
      ) {
        callback(new Error("请至少添加一个SPU销售属性值名称"));
        return;
      }
      callback();
    },
    // 添加销售属性
    addSaleAttrItemHandle() {
      const [id, name] = this.addSaleAttrItem.split(":");
      this.formData.spuSaleAttrList.push({
        baseSaleAttrId: +id,
        saleAttrName: name,
        spuSaleAttrValueList: [],
        isShow: false,
      });
      // 清空已选中的销售属性
      this.addSaleAttrItem = "";
    },
    // 添加销售属性值名称--进入编辑状态
    addSaleAttrValue(row) {
      row.isShow = true;
      this.$nextTick(() => {
        this.$refs.btnRef.focus();
      });
    },
    // 添加销售属性值名称
    loseBlur(row, index) {
      row.isShow = false;
      if (this.saleAttrName) {
        row.spuSaleAttrValueList.push({
          baseSaleAttrId: row.baseSaleAttrId,
          saleAttrValueName: this.saleAttrName,
        });
      }
      // 过滤销售属性值名称列表为空的销售属性
      this.filterSpuSaleAttrList();
      this.saleAttrName = "";
    },
    // 移除销售属性值名称
    removeSaleAttrValue(row, index) {
      row.spuSaleAttrValueList.splice(index, 1);
      // 过滤销售属性值名称列表为空的销售属性
      this.filterSpuSaleAttrList();
    },
    // 移除销售属性
    removeSaleAttr(index) {
      this.formData.spuSaleAttrList.splice(index, 1);
    },
    // 过滤销售属性值名称列表为空的销售属性
    filterSpuSaleAttrList() {
      this.formData.spuSaleAttrList = this.formData.spuSaleAttrList.filter(
        (item) => item.spuSaleAttrValueList.length
      );
    },
    // 获取SPU销售属性列表
    async getBaseSaleAttrList() {
      const res = await this.$api.getBaseSaleAttrList();
      this.baseSaleAttrList = res.data;
    },
    // 获取SPU品牌列表
    async getSpuTrademarkList() {
      const res = await this.$api.getSpuTrademarkList();
      this.spuTrademarkList = res.data;
    },
    // 搜集上传成功的图片数据
    uploadSuccess(response, file, fileList) {
      this.formData.spuImageList = fileList;
      this.$refs.formRef.clearValidate(["spuImageList"]);
    },
    // SPU图片上传
    beforeAvatarUpload(file) {
      const imgType = ["image/jpeg", "image/png", "image/gif"];
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!imgType.some((item) => item === file.type)) {
        this.$message({
          message: "上传的图片只能是 JPG / PNG / GIF 格式!",
          type: "error",
        });
        return imgType && isLt2M;
      }
      if (!isLt2M) {
        this.$message({
          message: "上传头像图片大小不能超过 2MB!",
          type: "error",
        });
      }
      return imgType && isLt2M;
    },
    // SPU图片预览
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
  computed: {
    ...mapState("category", ["category3Id"]),
    ...mapState("spu", ["spuSaleAttrListItem"]),
    newBaseSaleAttrList() {
      return this.baseSaleAttrList.filter((baseSaleAttr) => {
        return !this.formData.spuSaleAttrList?.some(
          (spuSaleAttr) => spuSaleAttr.baseSaleAttrId === baseSaleAttr.id
        );
      });
    },
    newSpuImageList() {
      return this.formData.spuImageList || [];
    },
  },
};
</script>

<style lang="scss" scoped>
.card-margin {
  margin-top: 20px;
}
.btn-margin {
  margin-left: 10px;
}
.table-margin {
  margin-top: 20px;
  // margin-bottom: 20px;
}
.sale-btn {
  width: 100px;
}
.tag-margin {
  margin-right: 5px;
}
</style>
